import * as pattern from '@/common/pattern';
import * as c from '@/services/consts';
import { CheckCircleFilled, CloseCircleFilled, UploadOutlined } from '@ant-design/icons';
import { DrawerForm } from '@ant-design/pro-components';
import ProForm, {
  ProFormDigit,
  ProFormGroup,
  ProFormInstance,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import {
  ActionType,
  EditableFormInstance,
  EditableProTable,
  ProColumns,
} from '@ant-design/pro-table';
import { Badge, Button, message, Tag, Tooltip, UploadProps } from 'antd';
import Upload, { RcFile } from 'antd/lib/upload';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';

type MyFormProps = {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: API.VpnServer[]) => Promise<void>;
  onSubmitReturn?: (record: API.VpnServer[]) => void;
};

const MyForm: React.FC<MyFormProps> = (props) => {
  const { visible, onCancel, onSubmit,onSubmitReturn } = props;
  if (!visible) {
    return <></>;
  }

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const editorFormRef = useRef<EditableFormInstance<API.VpnServerBatchModel>>();
  const [uploadFileName, setUploadFileName] = useState<string | undefined>(
    undefined,
  );
  const [loadingButtonUpload, setLoadingButtonUpload] =
    useState<boolean>(false);
  // const [formInputVisible, setFormInputVisible] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<API.VpnServerBatchModel[] | undefined>([]);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const { getVpnGroupExTrees, getVpnGroupTitle, supplierOptions, getSupplier,getDeployConfigOptions } =
    useModel('useGlobalModel', (model) => ({
      // getProductVpnGroupTrees: model.getProductVpnGroupTrees,
      getVpnGroupTitle: model.getVpnGroupTitle,
      supplierOptions: model.supplierOptions,
      getSupplier: model.getSupplier,
      // getProductOptions: model.getProductOptions,
      // supplyAreaOptions: model.supplyAreaOptions,
      // getSupplyArea: model.getSupplyArea,
      getVpnGroupExTrees: model.getVpnGroupExTrees,
      getDeployConfigOptions: model.getDeployConfigOptions,
    }));

  const getRandomPort = () => {
    return Math.floor(Math.random() * 10000 + 10000);
  };

  const loadGroupTreeData = async (params: { [key: string]: any }) => {
    const treeData = getVpnGroupExTrees(params?.productId);
    // const treeData = getProductVpnGroupTrees(params.productId);
    return Promise.resolve(treeData);
  };

  const getSshUserOptions = () => {
    let options = getDeployConfigOptions(3);
    return options.map((element) => {
      return {label:element.label, value: element.value};
    });
  }
  const getSshUserId = (user: string | undefined) => {
    if(user){
      let options = getDeployConfigOptions(3);
      for(let d of options){
        if(d.label == user) return d.value;
      }
    }
    return undefined;
  }

  const handleAddRecord = async () => {
    try {
      const values = await formRef.current?.validateFields();
      //console.log(values);
      let datas = editorFormRef.current?.getRowsData?.() ?? [];
      let myId = datas.length + 1;
      if (datas) {
        for (let d of datas) {
          if (d.instanceId == values.instanceId) {
            message.error('列表中已经存在该实例ID');
            return;
          }
          if (d.name == values.name) {
            message.error('列表中已经存在该名称');
            return;
          }
          if (d.ip == values.ip) {
            message.error('列表中已经存在该IP');
            return;
          }
          // if(d.id == myId.toString()){
          //   myId ++;
          // }
        }
      }
      let rndPort = getRandomPort();
      let rows: API.VpnServerBatchModel[] = [];
      for (let item of datas) {
        rows.push(item);
      }
      let record: API.VpnServerBatchModel = {
        id: myId.toString(), //(Math.random() * 100000000).toFixed(0),
        // netId: (Math.random() * 1000000).toFixed(0).toString(),
        // id:getUniqueId(rows),
        instanceId: values.instanceId,
        name: values.name,
        ip: values.ip,
        pingPort: values.pingPort ?? rndPort,
        port: values.port ?? rndPort + 1,
        maxUser: values.maxUser,
        maxBandwidth: values.maxBandwidth,
        status: values.status,
        remark: values.remark,

        // infoIpPool: values.ipPool,
        infoPrice: values.price,
        infoSshPort: values.sshPort,
        infoSshUser: values.sshUser,
        infoSshPassword: values.sshPassword,
        infoSshKeyId: values.sshKey,
        infoEnableUdp: values.enableUdp,
        infoAuth: values.auth,
        infoWorkMode: values.workMode,
        infoServerName: values.idcServerName,
        infoServerRegion: values.idcServerRegion,
        infoBandwidth: values.bandwidth,
        serverType: values.serverType,
        supplierId: values.supplierId,
        serverTypeName: c.getServerType(values.serverType)?.label,
        supplierName: getSupplier(values.supplierId)?.name,
        // supplyAreaName : getSupplyArea(values.supplyAreaId)?.name,
        // addedDate: values.addedDate ? moment(values.addedDate).toDate() : undefined,

        // netIp: values.outIp,
        // netPortBegin: values.portBegin,
        // netPortEnd: values.portEnd,
        // netOutIp: values.bindIp,
        groupIds: values.groupIds,
        groupName: getVpnGroupTitle(values.groupIds),
      };
      rows.push(record);
      // console.log(rows);
      // myId++;

      setDataSource(rows);
      setEditableRowKeys(() => rows.map((item) => item.id));
      //actionRef.current?.addEditRecord?.(record);
      formRef.current?.setFieldValue('instanceId', values.instanceId + 1);

      // formRef.current?.setFieldValue("name", "");
      // formRef.current?.setFieldValue("instanceId", "");
      // formRef.current?.setFieldValue("ip", "");
      // formRef.current?.setFieldValue("remark", "");
      // formRef.current?.setFieldValue("price", "");
    } catch (errInfo) {
      // message.warn('请正确填写数据');
    }
  };

  const handleFormSubmit = async () => {
    let datas = editorFormRef.current?.getRowsData?.();
    if (!datas || datas.length < 1) {
      message.error('请填写正确数据');
      return;
    }
    let records: API.VpnServer[] = [];
    for (let d of datas) {
      // let netModel : API.VpnServerNet[] | undefined = undefined;
      // if(d.netIp){
      //   netModel = [{
      //     id: d.netId,
      //     ip: d.netIp,
      //     outIp: d.netOutIp,
      //     status: true
      //   }];
      // }

      records.push({
        id: d.id,
        instanceId: d.instanceId,
        name: d.name,
        ip: d.ip,
        port: d.port,
        pingPort: d.pingPort,
        maxBandwidth: d.maxBandwidth,
        maxUser: d.maxUser,
        status: d.status,
        groupIds: d.groupIds,
        groupSort: 0,
        remark: d.remark,
        // netConfig: netModel,
        serverInfo: {
          price: d.infoPrice,
          sshPort: d.infoSshPort,
          sshUser: d.infoSshUser,
          sshPassword: d.infoSshPassword,
          serverName: d.infoServerName,
          serverRegion: d.infoServerRegion,
          sshKeyId: d.infoSshKeyId,
          workMode: d.infoWorkMode,
          auth: d.infoAuth,
          enableUdp: d.infoEnableUdp,
          bandwidth: d.infoBandwidth,
        },
        serverType: d.serverType,
        supplierId: d.supplierId,
        addedDate: d.addedDate,
      });
    }
    //console.log(records);
    // onSubmit(records);
    if(onSubmitReturn){
      onSubmitReturn(records);
    }
    else{
      onSubmit(records);
    }
  };

  const excelUploadProps: UploadProps = {
    name: 'excelFile',
    showUploadList: false,
    action: '/admin-api/vpnserver/ExcelVpnServer',
    headers: {
      authorization: 'authorization-text',
    }, //http://localhost:29999
    beforeUpload(file: RcFile) {
      setLoadingButtonUpload(true);
      setUploadFileName(file.name);
      let groupIds = formRef.current?.getFieldValue('groupIds');
      if (!groupIds) {
        message.error('请先选择分组');
        setLoadingButtonUpload(false);
        return false;
      }
      //console.log(file);
      const isExcelFile =
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel';
      if (!isExcelFile) {
        message.error('只能上传Excel文件');
        setLoadingButtonUpload(false);
      }
      const isFileSize = file.size / 1024 < 100;
      if (!isFileSize) {
        message.error('文件不能大于 100K');
        setLoadingButtonUpload(false);
      }
      return isExcelFile && isFileSize;
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        //console.log(info, info.file.response);
        let result = info.file.response;
        if (result && result.data && result.data.length > 0) {
          //console.log(result);
          let port = formRef.current?.getFieldValue('port');
          let pingPort = formRef.current?.getFieldValue('pingPort');
          let maxUser = formRef.current?.getFieldValue('maxUser');
          let maxBandwidth = formRef.current?.getFieldValue('maxBandwidth');
          let status = formRef.current?.getFieldValue('status');
          let remark = formRef.current?.getFieldValue('remark');
          let groupIds = formRef.current?.getFieldValue('groupIds');
          let groupName = getVpnGroupTitle(formRef.current?.getFieldValue('groupIds'),);
          let serverType = formRef.current?.getFieldValue('serverType');
          let serverTypeName = c.getServerType(formRef.current?.getFieldValue('serverType'),)?.label;
          let supplierId = formRef.current?.getFieldValue('supplierId');
          let supplierName = getSupplier(supplierId)?.name;
          let sshPort = formRef.current?.getFieldValue('sshPort');
          let sshUser = formRef.current?.getFieldValue('sshUser');
          let sshKey = formRef.current?.getFieldValue('sshKeyId');
          // let enableUdp = formRef.current?.getFieldValue('enableUdp');
          // let auth = formRef.current?.getFieldValue('auth');
          let workMode = formRef.current?.getFieldValue('workMode');
          let bandwidth = formRef.current?.getFieldValue('bandwidth');

          // let addedDate = formRef.current?.getFieldValue("addedDate");
          // infoIpPool: item.serverInfo?.ipPool,
          // netId: (Math.random() * 1000000).toFixed(0).toString(),
          // netIp: item.netConfig ? item.netConfig[0].ip : undefined,
          // netOutIp: item.netConfig ? item.netConfig[0].outIp : undefined,

          let datas = editorFormRef.current?.getRowsData?.() ?? [];
          let myId = datas.length + 1;
          let rows: API.VpnServerBatchModel[] = [];
          for (let item of datas) {
            rows.push(item);
          }
          for (let item of result.data) {
            console.log(item);
            let rndPort = getRandomPort();
            let record: API.VpnServerBatchModel = {
              id: myId.toString(), //(Math.random() * 100000000).toFixed(0),
              // id:getUniqueId(rows),
              instanceId: item.instanceId,
              name: item.name,
              ip: item.ip,

              infoPrice: item.serverInfo?.price,
              infoServerName: item.serverInfo?.serverName,
              infoServerRegion: item.serverInfo?.serverRegion,
              infoSshPort: item.serverInfo?.sshPort ?? sshPort,
              infoSshPassword: item.serverInfo?.sshPassword,
              infoSshUser: getSshUserId(item.serverInfo?.sshUser) ?? sshUser,
              infoSshKeyId: sshKey,
              infoEnableUdp: item.serverInfo?.enableUdp,
              infoAuth: item.serverInfo?.auth,
              infoWorkMode: item.serverInfo?.workMode ?? workMode,
              infoBandwidth: item.serverInfo?.bandwidth ?? bandwidth,

              port: port ?? rndPort + 1,
              pingPort: pingPort ?? rndPort,
              maxUser: maxUser,
              maxBandwidth: maxBandwidth,
              status: status,
              remark: remark ? remark : item.serverInfo?.remark,
              groupIds: groupIds,
              groupName: groupName,
              serverType: serverType,
              serverTypeName: serverTypeName,
              supplierId: supplierId,
              // supplyAreaId: supplyAreaId,
              supplierName: supplierName,
              // supplyAreaName: supplyAreaName,
              // addedDate: addedDate
            };
            rows.push(record);
            //actionRef.current?.addEditRecord?.(record);
            myId++;
          }
          //console.log(datas);
          //console.log(rows);
          setDataSource(rows);
          setEditableRowKeys(() => rows.map((item) => item.id));
          //actionRef.current?.reload();
        } else {
          message.warning(`${info.file.name}，没有有效数据`);
        }
        setLoadingButtonUpload(false);
        // message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name}  文件上传失败.`);
      }
    },
  };

  // const { hasRight } = useModel('useAuthModel');

  let columns: ProColumns<API.VpnServerBatchModel>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      width: 50,
      readonly: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      readonly: true,
      width: 50,
      align: 'center',
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '分组',
      dataIndex: 'groupName',
      width: 200,
      ellipsis: true,
      readonly: true,
    },
    {
      title: '实例ID',
      dataIndex: 'instanceId',
      readonly: true,
      width: 80,
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      readonly: true,
      width: 120,
    },
    {
      title: '名称',
      dataIndex: 'name',
      readonly: true,
      width: 150,
    },
    {
      title: '服务器标识',
      dataIndex: 'infoServerName',
      readonly: true,
      width: 200,
    },
    {
      title: '服务器区域',
      dataIndex: 'infoServerRegion',
      readonly: true,
      width: 200,
    },
    {
      title: '带宽',
      dataIndex: 'infoBandwidth',
      readonly: true,
      width: 50,
    },
    {
      title: '服务端口',
      dataIndex: 'port',
      readonly: true,
      width: 80,
    },
    {
      title: '测速端口',
      dataIndex: 'pingPort',
      readonly: true,
      width: 80,
    },
    {
      title: '用户',
      dataIndex: 'maxUser',
      readonly: true,
      width: 50,
    },
    {
      title: '总调度带宽',
      dataIndex: 'maxBandwidth',
      readonly: true,
      width: 150,
    },
    {
      title: '类型',
      dataIndex: 'serverTypeName',
      readonly: true,
      width: 50,
    },
    {
      title: '供应商',
      dataIndex: 'supplierName',
      readonly: true,
      width: 120,
    },
    {
      title: '价格',
      dataIndex: 'infoPrice',
      readonly: true,
      width: 50,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      readonly: true,
      width: 60,
    },
    {
      title: 'ssh端口',
      dataIndex: 'infoSshPort',
      width: 70,
      readonly: true,
    },
    {
      title: 'ssh用户',
      dataIndex: 'infoSshUser',
      width: 70,
      readonly: true,
    },
    {
      title: 'ssh密码',
      dataIndex: 'infoSshPassword',
      width: 70,
      readonly: true,
    },
    // {
    //   title: 'ssh key',
    //   dataIndex: 'infoSshKey',
    //   width: 70,
    //   readonly: true,
    // },
    {
      title: '传输协议',
      dataIndex: 'infoWorkMode',
      width: 80,
      readonly: true,
    },
    {
      title: '使用UDP',
      dataIndex: 'infoEnableUdp',
      width: 90,
      // readonly: true,
    },
    {
      title: '开启授权',
      dataIndex: 'infoAuth',
      width: 90,
      // readonly: true,
    },

    {
      title: '操作',
      valueType: 'option',
      width: 50,
      render: () => {
        return null;
      },
    },
    // {
    //   title: '操作',
    //   valueType: 'option',
    //   width: 50,
    //   render: (text, record, _, action) => [
    //     <a
    //       key="delete"
    //       onClick={() => {
    //         setDataSource(dataSource.filter((item) => item.id !== record.id));
    //       }}
    //     >
    //       删除
    //     </a>,
    //   ],
    // },
  ];

  return (
    <DrawerForm<API.VpnServerBatchModel>
      open={visible}
      title="批量添加服务器"
      // formRef={formRef}
      autoFocusFirstInput
      width={1600}
      onFinish={handleFormSubmit}
      drawerProps={{
        onClose: onCancel,
        maskClosable: false,
      }}
    >
      <EditableProTable<API.VpnServerBatchModel>
        rowKey="id"
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        name="table"
        recordCreatorProps={false}
        style={{
          minHeight: 900,
          overflowX:'scroll',
          overflowY: 'auto',
          marginTop: -20,
          marginLeft: -20,
          marginRight: -20,
          marginBottom: -30,
        }}
        columnEmptyText={''}
        actionRef={actionRef}
        editableFormRef={editorFormRef}
        columns={columns}
        search={false}
        pagination={false}
        editable={{
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDoms) => {
            return [defaultDoms.delete];
          },
          // type: 'single',
          // onValuesChange: (record, recordList) => {
          //   setDataSource(recordList);
          // },
        }}
        request={async () => ({
          data: dataSource,
          success: true,
        })}
        // value={dataSource}
        // onChange={setDataSource}
        params={{ d: dataSource }}
        scroll={{ x: 1800, y: 'auto' }}
        tableExtraRender={(_, data) => (
          <ProForm<API.VpnServerBatchModel>
            formRef={formRef}
            layout="horizontal"
            style={{
              margin: 'auto',
              marginTop: 0,
              marginLeft: 25,
              width: 1540,
              height: 215,
            }}
            submitter={{
              render: (props, doms) => {
                return [];
              },
            }}
            onFinish={handleFormSubmit}
          >
            <ProFormGroup style={{ marginTop: 20 }}>
              <ProFormTreeSelect
                name="groupIds"
                label="分组"
                placeholder="请选择分组"
                allowClear={false}
                width={450}
                // secondary
                rules={[{ required: true, message: '请选择分组' }]}
                request={loadGroupTreeData}
                // tree-select args
                fieldProps={{
                  listHeight: 500,
                  showArrow: true,
                  showSearch: true,
                  treeCheckable: true,
                  multiple: true,
                  treeDefaultExpandAll: true,
                  treeNodeFilterProp: 'title',
                  maxTagCount: 1,
                }}
              />
              <ProFormSelect
                name="serverType"
                label="类型"
                placeholder="请选择服务器类型"
                width={100}
                allowClear={true}
                options={c.ServerTypes}
              />
              <ProFormDigit
                name="port"
                label="服务端口"
                width={100}
                min={1}
                max={65535}
                // initialValue={16231}
                // rules={[{ required: true, message: '请输入服务端口' }]}
                // placeholder="请输入服务端口"
              />
              <ProFormDigit
                name="pingPort"
                label="测速端口"
                width={100}
                min={0}
                max={65535}
                // initialValue={16230}
                // rules={[{ required: true, message: '请输入测速端口' }]}
                // placeholder="请输入测速端口"
              />
              <ProFormDigit
                name="maxUser"
                label="用户限制"
                width={100}
                min={0}
                max={10000}
                initialValue={0}
                rules={[{ required: true, message: '请输入用户限制' }]}
                placeholder="最大在线用户数量"
              />
              <ProFormDigit
                name="maxBandwidth"
                label="总调度带宽(MB)"
                width={100}
                min={0}
                max={102400}
                initialValue={0}
                rules={[{ required: true, message: '请输入带宽限制' }]}
                placeholder="服务器最大带宽"
                // addonAfter={<span className="ant-form-item-extra">(MB)</span>}
              />
              {/* <ProFormDigit
            name="portBegin"
            label="开始端口"
            width={100}
            min={1024}
            max={65535}
            initialValue={16231}
            rules={[
              { required: true, message: '请输入开始端口' },
              {
                transform: (value) => parseInt(value, 10),
                validator: (rule, value) => {  
                  if (value < 1024 || value > 65535) {
                    return Promise.reject(
                      new Error('开始端口须在1024-65535之间'),
                    );
                  }
                  
                  const portEndValue = formRef.current?.getFieldValue('portEnd');

                  if (value > portEndValue) {
                    return Promise.reject(new Error('开始端口须小于结束端口'));
                  }
                  if (portEndValue - value > 50) {
                    return Promise.reject(
                      new Error('端口范围须小于50'),
                    );
                  }
                  return Promise.resolve();
                },
              },
            ]}
            placeholder="请输入开始端口"
          />
          <ProFormDigit
            name="portEnd"
            label="结束端口"
            width={100}
            min={1024}
            max={65535}
            initialValue={16234}
            rules={[
              { required: true, message: '请输入结束端口' },
              {
                transform: (value) => parseInt(value, 10),
                validator: (rule, value) => {  
                  if (value < 1024 || value > 65535) {
                    return Promise.reject(
                      new Error('结束端口须在1024-65535之间'),
                    );
                  }
                  
                  const portBeginValue = formRef.current?.getFieldValue('portBegin');

                  if (value < portBeginValue) {
                    return Promise.reject(new Error('结束端口须大于开始端口'));
                  }
                  if (value - portBeginValue > 50) {
                    return Promise.reject(
                      new Error('端口范围须小于50'),
                    );
                  }
                  return Promise.resolve();
                },
              },
            ]}
            placeholder="请输入结束端口"
          /> */}
              {/* <ProFormDateTimePicker
            name="addedDate"
            label="上架日期"
            fieldProps={{
              showTime: false,
              format: 'YYYY-MM-DD',
            }}
          /> */}
              <ProFormText name="remark" label="服务器备注" width={150} />
              <ProFormText
                name="price"
                label="价格"
                width={100}
                placeholder="价格"
              />
              <ProFormSwitch
                name="status"
                label="状态"
                initialValue={true}
                fieldProps={{
                  defaultChecked: false,
                }}
              />
            </ProFormGroup>

            <ProFormGroup style={{ marginTop: 20 }}>
              <ProFormText
                name="name"
                label="名称"
                width={240}
                rules={[{ required: true, message: '请输入名称' }]}
                placeholder="请输入名称"
              />
              <ProFormDigit
                name="instanceId"
                label="实例ID"
                width={110}
                min={1}
                max={2099999999}
                rules={[{ required: true, message: '请输入实例ID' }]}
                placeholder="请输入实例ID"
              />
              <ProFormText
                name="ip"
                label="IP"
                width={150}
                rules={[
                  { required: true, message: '请输入IP' },
                  {
                    pattern: pattern.IP,
                    message: '请输入有效的IP',
                  },
                ]}
                placeholder="请输入IP"
              />

              <ProFormSelect
                name='sshUser'
                label="SSH用户"
                options={getSshUserOptions()}
              />
              <ProFormText name="sshPassword" width={100} label="SSH密码" />
              <ProFormDigit
                name="sshPort"
                label="SSH端口"
                width={100}
                min={1}
                max={65535}
              />
              <ProFormSelect
                name='sshKeyId'
                label="SSH Key"
                options={getDeployConfigOptions(2)}
              />
              <ProFormSelect
                name='workMode'
                label="传输协议"
                rules={[{ required: true, message: '请选择传输协议' }]}
                options={[{label:'老协议', value:0},{label:'新协议', value:1}]}
                initialValue={0}
              />
              <ProFormDigit
                name="bandwidth"
                label="带宽(Mb)"
                width={100}
                min={1}
                max={102400}
                placeholder="服务器带宽"
                // addonAfter={<span className="ant-form-item-extra">(MB)</span>}
              />
              <ProFormSwitch
                name='enableUdp'
                label="UDP"
                initialValue={false}
              />
              <ProFormSwitch
                name='auth'
                label="授权"
                initialValue={false}
              />

            </ProFormGroup>

            <ProFormGroup style={{ marginTop: 20 }}>
              <ProFormSelect
                name="supplierId"
                label="服务器供应商"
                placeholder="请选择供应商"
                width={240}
                allowClear={true}
                options={supplierOptions}
                showSearch={true}
              />
              
              <ProFormText
                name="idcServerName"
                label="服务器标识"
                width={240}
              />
              <ProFormText
                name="idcServerRegion"
                label="服务器区域"
                width={240}
              />

              <Button
                type="primary"
                key="submit"
                style={{ marginTop: 28 }}
                onClick={async () => {
                  handleAddRecord();
                  // formRef.current?.submit();
                  // actionRef.current?.addEditRecord?.({
                  //   id: (Math.random() * 1000000).toFixed(0),
                  // },);
                  // let tmpDs = dataSource;
                  // tmpDs.push({id: (Math.random() * 1000000).toFixed(0)});
                  // setDataSource(tmpDs)
                }}
              >
                加入
              </Button>

              <Tooltip
                placement="bottom"
                title={
                  <span>
                    <p>Excel文件 列标题栏 需包含：</p>
                    <p></p>
                    <p>名称、实例ID、IP、价格[可选]</p>
                    <p>其他信息使用界面表单中的数据</p>
                  </span>
                }
                overlayInnerStyle={{ width: 400 }}
              >
                <Upload {...excelUploadProps} maxCount={1}>
                  <div>
                    <Button
                      icon={<UploadOutlined />}
                      danger
                      loading={loadingButtonUpload}
                      style={{ marginTop: 28 }}
                    >
                      导入
                    </Button>
                  </div>
                  {uploadFileName ? (
                    <div>
                      <Tag style={{ maxWidth: 320, overflow: 'hidden' }}>
                        {uploadFileName}
                      </Tag>
                    </div>
                  ) : (
                    ''
                  )}
                </Upload>
              </Tooltip>

            </ProFormGroup>

          </ProForm>
        )}
      />

    </DrawerForm>
  );
};

export default MyForm;
